<?php

namespace Modules\Common\Models;

use Illuminate\Support\Str;
use Modules\Common\Models\Validation\FileValidation;


class File extends BaseModel
{
    protected $connection = 'mysql';
    protected $table = 'files';
    use FileValidation;

    public static function findByEncryptedId($encryptedId): self
    {
        return self::find(self::decryptId($encryptedId));
    }

    public static function getRealPath($fileId)
    {
        return self::find($fileId)->real_path;
    }

    public function getRealpathAttribute()
    {
        return storage_path('app/public/' . $this->path);
    }

    public static function getUrl(int $fileId)
    {
        $path = self::whereKey($fileId)->value('path');

        // return $path ? asset('storage/' . $path) : '';
         return $path;
    }


    public static function packZipFile(array $paths)
    {
        $realPath = storage_path('app/public/download/common-zip-file/' . date('Y-m-d'));
        if (!file_exists($realPath)) {
            mkdir($realPath, 0777, true);
        }
        $zipName = date('Y-m-d H-i-s') . '.zip';
        $zipPath = $realPath . DIRECTORY_SEPARATOR . $zipName;
        $zip = new \ZipArchive;
        if ($zip->open($zipPath, \ZipArchive::CREATE) === TRUE) {
            foreach ($paths as $file) {
                $zip->addFile($file, Str::afterLast($file, DIRECTORY_SEPARATOR));
            }
            $zip->close();
        }
        return Str::after($zipPath, storage_path('app/public'));
    }

}
